<template>
  <el-form :model="form" label-width="120px" :rules="rules" status-icon>
    <h1>梵客登录</h1>
    <el-form-item label="用户名" size="large" prop="username">
      <el-input v-model="form.username" />
    </el-form-item>
    <el-form-item label="密码" size="large" prop="password">
      <el-input v-model="form.password" type="password" />
    </el-form-item>
    
    <el-form-item label="验证码" size="large" prop="verifyCode">
      <el-input v-model="form.verifyCode" style="display: inline-block;width: 200px;margin-right:20px ;" />
      <el-image :src="'data:image/jpeg;base64,'+captchaImage" @click="getCaptchaImage"/>
    </el-form-item>
    <el-form-item size="large">
      <el-button type="primary" @click="onSubmit" >登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { getCurrentInstance,reactive,onBeforeMount,ref } from "vue"
import { useStore } from '@/stores'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance();
const store = useStore()
const router=useRouter()

let captchaImage=ref()
const form = reactive({
  username: '',
  password: '',
  verifyCode:'',
  uuid:''
})

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }   
  ],
  password:[
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  verifyCode:[
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ]
})
async function getCaptchaImage(){
  let { data: res} = await proxy.$http({
		  method:'get',
		  url:'/api/captchaImage'
	})
  captchaImage.value=res.data.img
  form.uuid=res.data.uuid
  console.log(captchaImage.value)
}

onBeforeMount(async ()=>{
    getCaptchaImage()
})

const onSubmit =  async () => {  
  let { data: res} = await proxy.$http({
		  method:'post',
		  data:form,
		  url:'/api/login'
	})
  console.log(res)
  if(res.code==200){
    store.setToken(res.data.token)
    console.log(store.token)
    store.setUser(res.data.user)
    ElMessage('登录成功！')
    if(res.data.user.userRole==='操作员')
      router.push('/home')
    else
      router.push('/admin')
  }else{
    form.password=''
    ElMessage('用户名密码错误！')
  }  
}
</script>

<style scoped>
h1{
  text-align: center;
  margin-bottom: 50px;
}
.el-form{
  width: 800px;
  margin:0 auto;
 
}
</style>
